package cn.chenfeifx.core.controls.skins;

import cn.chenfeifx.core.common.FxUtil;
import cn.chenfeifx.core.controls.CFAvatar;
import javafx.beans.binding.Bindings;
import javafx.geometry.Rectangle2D;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.SkinBase;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

public class CFAvatarSkin extends SkinBase<CFAvatar> {

    private final ImageView imageView;

    public CFAvatarSkin(CFAvatar control) {
        super(control);
        imageView = new ImageView();
        /*
        imageView.setPreserveRatio(true);
        imageView.setCache(true);
        imageView.setSmooth(true);
        */
        bindProperty(control);
        getChildren().add(imageView);
    }

    /**
     * 绑定属性
     *
     * @param control
     */
    private void bindProperty(CFAvatar control) {
        imageView.imageProperty().bind(Bindings.createObjectBinding(() -> {
            Image image = control.getImage();
            double width = image.getWidth();
            double height = image.getHeight();
            if (width == height) {
                return image;
            }
            double min = Math.min(width, height);
            double max = Math.max(width, height);
            /*
             * 当图片不为正方形时，使用快照功能截取图片为正方形（中间位置截取）
             */
            SnapshotParameters snapshotParameters = new SnapshotParameters();
            snapshotParameters.setViewport(new Rectangle2D((max - min) / 2, 0, min, min));
            //
            return new ImageView(image).snapshot(snapshotParameters, null);
        }, control.imageProperty()));
        imageView.fitHeightProperty().bind(control.sizeProperty());
        imageView.fitWidthProperty().bind(control.sizeProperty());
        //圆角绑定
        FxUtil.clipRect(imageView, control.radiusProperty());
    }

    @Override
    protected void layoutChildren(double contentX, double contentY, double contentWidth, double contentHeight) {
        super.layoutChildren(contentX, contentY, contentWidth, contentHeight);
    }
}
